package com.jeeplus.cms.common;

import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Sawyer
 * @date 2020-12-23
 */
@Component
@Getter
@Setter
public class CmsProperties {

    /**
     * 管理基础路径
     */
    @Value("${adminPath}")
    private String adminPath;

    /**
     * 前端基础路径
     */
    @Value("${frontPath}")
    private String frontPath;

    /**
     * 网站URL后缀
     */
    @Value("${urlSuffix}")
    private String urlSuffix;

    private String baiduAk;

    @JsonIgnore
    private Map<String, Object> propertyValMap = new HashMap<>(16);

    @PostConstruct
    public void init() throws IllegalAccessException {
        Map<String, Field> fieldMap = ReflectUtil.getFieldMap(CmsProperties.class);
        for (Map.Entry<String, Field> entry : fieldMap.entrySet()) {
            if (!"propertyValMap".equals(entry.getKey())) {
                propertyValMap.put(entry.getKey(), entry.getValue().get(this));
            }
        }
    }

    /**
     * 动态获取配置,主要用于提供前端
     *
     * @param propertyName 属性名
     * @return val
     */
    public Object getConfig(final String propertyName) {
        return propertyValMap.getOrDefault(propertyName, "");
    }


    /**
     * 获取工程路径
     *
     * @return
     */
    public static String getProjectPath() {
        // 如果配置了工程路径，则直接返回，否则自动获取。
        String projectPath = "";
        try {
            File file = new DefaultResourceLoader().getResource("").getFile();
            while (true) {
                File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
                if (f.exists()) {
                    break;
                }
                if (file.getParentFile() != null) {
                    file = file.getParentFile();
                } else {
                    break;
                }
            }
            projectPath = file.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return projectPath;
    }

    @Override
    public String toString() {
        return "CmsProperties{" +
                "adminPath='" + adminPath + '\'' +
                ", frontPath='" + frontPath + '\'' +
                ", urlSuffix='" + urlSuffix + '\'' +
                ", baiduAk='" + baiduAk + '\'' +
                '}';
    }
}
